from flask import Flask, jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
from flask_migrate import Migrate
from flask_cors import CORS
from config import Config
from .models import db, User, Conversation, SystemSetting # Ensure models are imported

# Initialize extensions (but not yet attached to an app)
# db defined in models.py
login_manager = LoginManager()
migrate = Migrate()

def create_app(config_class=Config):
    app = Flask(__name__, instance_relative_config=True)
    app.config.from_object(config_class)

    # Ensure instance folder exists
    try:
        os.makedirs(app.instance_path)
    except OSError:
        pass # Already exists

    # Initialize Flask extensions here
    db.init_app(app)
    login_manager.init_app(app)
    migrate.init_app(app, db)
    CORS(app, supports_credentials=True) # Allow all origins for development, refine for production

    # Configure Flask-Login
    login_manager.login_view = 'auth.login' # The route for login
    login_manager.login_message_category = 'info'
    login_manager.session_protection = "strong"

    @login_manager.unauthorized_handler
    def unauthorized():
        return jsonify(message="Authentication required to access this resource."), 401

    # 创建 API 蓝图
    from app.api import bp as api_bp
    
    # 注册子蓝图到 API 蓝图
    from app.auth import bp as auth_bp
    api_bp.register_blueprint(auth_bp)
    
    from app.chat import bp as chat_bp
    api_bp.register_blueprint(chat_bp)
    
    from app.admin import bp as admin_bp
    api_bp.register_blueprint(admin_bp)
    
    # 注册 API 蓝图到应用
    app.register_blueprint(api_bp)
    
    # 移除或注释掉原来的蓝图注册
    # app.register_blueprint(auth_bp)
    # app.register_blueprint(chat_bp)
    # app.register_blueprint(admin_bp)

    with app.app_context():
        db.create_all()  # Create tables if they don't exist

        # Create a default admin user and initial settings if they don't exist
        if not User.query.filter_by(email=app.config['ADMIN_EMAIL']).first():
            admin_user = User(email=app.config['ADMIN_EMAIL'], is_admin=True)
            admin_user.set_password(app.config['ADMIN_PASSWORD'])
            db.session.add(admin_user)
            app.logger.info(f"Admin user {app.config['ADMIN_EMAIL']} created.")
        
        # Initial system settings (if not already present)
        default_settings = {
            'llm_model': app.config.get('DEFAULT_LLM_MODEL'),
            'openai_api_base_admin': app.config.get('OPENAI_API_BASE'),
            'system_prompt': 'You are a helpful assistant.'
            # Do not store API key by default in DB, rely on app config unless admin explicitly sets it
        }
        for key, value in default_settings.items():
            if not SystemSetting.query.filter_by(key=key).first():
                setting = SystemSetting(key=key, value=value)
                db.session.add(setting)
                app.logger.info(f"Default setting '{key}' added to database.")
        
        db.session.commit()

        
    app.logger.info("Flask App Created and Configured.")
    app.logger.info(f"Database URI: {app.config['SQLALCHEMY_DATABASE_URI']}")
    app.logger.info(f"OpenAI API Base: {app.config['OPENAI_API_BASE']}")
    if app.config.get('OPENAI_API_KEY'):
        app.logger.info("OpenAI API Key is set.")
    else:
        app.logger.warning("OpenAI API Key is NOT set in config.")


    return app

# Import models here at the bottom to avoid circular dependencies with db
# This is already handled by importing db, User, Conversation from .models
import os # Import os here for makedirs
